package com.js.nickcar.module.login;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.js.nickcar.R;
import com.js.nickcar.base.BaseFragment;
import com.js.nickcar.module.home.HomeFragment;
import com.js.nickcar.utils.StringUtils;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by LZY on 2017/9/28.
 */

public class LoginFragment extends BaseFragment<LoginPresenter> implements LoginView {
    @Bind(R.id.et_phone)
    EditText mEtPhone;
    @Bind(R.id.tv_getCode)
    TextView mTvGetCode;
    @Bind(R.id.et_code)
    EditText mEtCode;
    @Bind(R.id.btn_login)
    Button mBtnLogin;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_login;
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    public static LoginFragment getInstance() {
        return new LoginFragment();
    }

    @Override
    protected void initData() {
        mEtPhone.setHint(StringUtils.getSizeSpan(getString(R.string.phone_num), 13));
        mEtCode.setHint(StringUtils.getSizeSpan(getString(R.string.ver_code), 13));
        showToast("我是版本3.0");
    }

    @OnClick({R.id.tv_getCode, R.id.btn_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_getCode:
                getCode();
                break;
            case R.id.btn_login:
                login();
                break;
        }
    }

    private void login() {
        mPresenter.login(mEtPhone.getText().toString(), mEtCode.getText().toString());
    }

    private void getCode() {
        mPresenter.getCode(mEtPhone.getText().toString());
    }

    @Override
    public void getCodeSuccess() {
        mTvGetCode.setText(mPresenter.getSurplusTime() + "s");
        mTvGetCode.setEnabled(false);
        mTvGetCode.postDelayed(countDownRunnable, 1000);
        showToast(getString(R.string.get_ver_code_success));
    }

    @Override
    public void loginSuccess() {
        replaceFragment(HomeFragment.getInstance());
    }

    private Runnable countDownRunnable = new Runnable() {
        @Override
        public void run() {
            if (mTvGetCode == null)
                return;
            int surplusTime = mPresenter.getSurplusTime();
            if (surplusTime > 0) {
                mTvGetCode.setText(surplusTime + "s");
                mTvGetCode.postDelayed(countDownRunnable, 1000);
            } else {
                mTvGetCode.setEnabled(true);
                mTvGetCode.setText(getString(R.string.get_ver_code));
            }
        }
    };
}
